package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.query.EmployeeQueryObject;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.JSONResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    //只是负责转发到员工页面
    @RequestMapping("view")
    public String view(){
        return "employee";
    }
    /*加载数据的列表页面*/
    @RequestMapping("query")
    @ResponseBody
    public PageResult query(EmployeeQueryObject qo){
        PageResult pageResult = employeeService.query(qo);
        return pageResult;
    }
    //根据员工id修改员工的状态
    @RequestMapping("changeState")
    @ResponseBody
    public JSONResult changeState(Long empId){
        try {
            employeeService.changeState(empId);
            return JSONResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return JSONResult.mark("操作失败");
        }
    }
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JSONResult saveOrUpdate(Employee employee){
        try {
            employeeService.saveOrUpdate(employee);
            return JSONResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return JSONResult.mark("保存失败");
        }
    }

    //验证当前用户名是否已存在
    @RequestMapping("getByUsername")
    @ResponseBody
    //只需其中一个权限即可
    @RequiresPermissions(value={"employee:getByUsername","获取用户"},logical = Logical.OR)
    public boolean getByUsername(String username, Long empId){
        Employee employee = employeeService.getByUsername(username);
        if(employee == null){
            return true;
        }else if(empId != null && employee.getId().equals(empId)){
            return false;
        }else {
            return false;
        }
    }

    //根据员工id找角色信息
    @RequestMapping("selectRoleByEmpId")
    @ResponseBody
    public List<Long> selectRoleByEmpId(Long empId){
        return employeeService.selectRoleByEmpId(empId);
    }
}
